﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace PubSubGeneric.WCFContracts.Utils
{
    public static class WCFSerializer
    {
        public static string Serialize(object obj)
        {
            return Serialize(obj, obj.GetType());
        }

        public static string Serialize(object obj, Type objType)
        {
            DataContractJsonSerializer Serializer = new DataContractJsonSerializer(objType);

            string objstr;

            using (var ms = new MemoryStream())
            {
                Serializer.WriteObject(ms, obj);
                using (var sr = new StreamReader(ms))
                {
                    sr.BaseStream.Position = 0;
                    objstr = sr.ReadToEnd();
                }
            }
            return objstr;
        }

        public static object DeSerialize(string objstr, string typeName)
        {
            return DeSerialize(objstr, Type.GetType(typeName));
        }

        public static object DeSerialize(string objstr, Type objType)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(objType);
            object obj;
            using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(objstr)))
            {
                //sw.BaseStream.Position = 0;
                obj = serializer.ReadObject(ms);
            }
            return obj;
        }
    }
}
